using HybridCLR;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;

public class LoadDll : MonoBehaviour
{
    private async void Start()
    {
        Assembly hotUpdateAss = null;
        
#if UNITY_EDITOR
        // Editor下无需加载，直接查找获得HotUpdate程序集
        hotUpdateAss = System.AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "HotUpdate");
#else
        // 在移动平台上异步加载dll
        string dllPath = $"{Application.streamingAssetsPath}/HotUpdate.dll.bytes";
        
        byte[] dllBytes = null;
        
        #if UNITY_ANDROID
        // Android平台使用UnityWebRequest加载
        using (UnityWebRequest www = UnityWebRequest.Get(dllPath))
        {
            await www.SendWebRequest();
            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"加载热更新DLL失败：{www.error}");
                return;
            }
            dllBytes = www.downloadHandler.data;
        }
        #elif UNITY_IOS
        // iOS平台使用UnityWebRequest加载
        using (UnityWebRequest www = UnityWebRequest.Get(dllPath))
        {
            await www.SendWebRequest();
            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError($"加载热更新DLL失败：{www.error}");
                return;
            }
            dllBytes = www.downloadHandler.data;
        }
        #else
        // 其他平台直接同步读取
        dllBytes = File.ReadAllBytes(dllPath);
        #endif
        
        try 
        {
            hotUpdateAss = Assembly.Load(dllBytes);
        }
        catch (Exception e)
        {
            Debug.LogError($"加载Assembly失败：{e.Message}");
            return;
        }
#endif

        if (hotUpdateAss != null)
        {
            try
            {
                Type type = hotUpdateAss.GetType("Hello");
                if (type != null)
                {
                    type.GetMethod("Run")?.Invoke(null, null);
                }
                else
                {
                    Debug.LogError("未找到Hello类型");
                }
            }
            catch (Exception e)
            {
                Debug.LogError($"执行热更新代码失败：{e.Message}");
            }
        }
    }
}
